package com.example.checkqufuface.View.QufuFaceProject;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.checkqufuface.Base.BaseActivity;
import com.example.baselibrary.Utils.LogUtil;
import com.example.checkqufuface.Utils.SelfToastUtil;
import com.example.baselibrary.Utils.StringUtil;
import com.example.baselibrary.Utils.TimeUtil;
import com.example.checkqufuface.Adapter.SearchFaceAdapter;
import com.example.checkqufuface.R;
import com.example.checkqufuface.RetrufitHelp.BaseSubscriber;
import com.example.checkqufuface.RetrufitHelp.ExceptionHandle;
import com.example.checkqufuface.RetrufitHelp.RetrofitClient;
import com.example.checkqufuface.bean.QufuQueryStaffReceiveTicketRequsetBean;
import com.example.checkqufuface.bean.QufuQueryStaffReceiveTicketResultBean;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderExceptionListener;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class FacePickActivity extends BaseActivity {

    private EditText etSearch;
    private Button btSearch;
    private TextView tvName;
    private TextView tvTicketType;
    private TextView tvTicketNumber;
    private TextView tvNumber;
    private TextView tvFace;
    private ImageView imFaceShow;

    // 曲阜 中身份证识别 新的集成
    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private IDCardReader idCardReader = null;
    private boolean bopen = false;
    private boolean bStoped = false;
    private int mReadCount = 0;
    private CountDownLatch countdownLatch = null;

    private Context mContext = null;
    private UsbManager musbManager = null;
    private final String ACTION_USB_PERMISSION = "com.example.scarx.idcardreader.USB_PERMISSION";

    private long timeNew;
    private long timeOld;
    private String OldID;

    private String certificateNo;

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        try {
                            OpenDevice();
                        } catch (Exception e) {

                        }
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                        //mTxtReport.setText("USB未授权");
                    }
                }
            }
        }
    };
    private Button btFaceOver;
    private Button btFaceGoto;
    private RecyclerView rvFaceShow;
    private List<QufuQueryStaffReceiveTicketResultBean.DataBean> searchDate;
    private LinearLayout llTicketRrsultShow;
    private LinearLayout llbtShow;
    private SearchFaceAdapter searchAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getView() {
        return R.layout.activity_face_pick;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //每次这个页面重现的是就去查询一次
        if (StringUtil.isNullOrEmpty(etSearch.getText().toString())) {
            return;
        }
        certificateNo = "";
        tvName.setText("");
        tvNumber.setText("");
        tvTicketType.setText("");
        tvTicketNumber.setText("");
        // 如果有数据，那么就去查询
        goToSearch(etSearch.getText().toString());

    }

    @Override
    public void init() {

        if (searchDate == null) {
            searchDate = new ArrayList<>();
        }

        mContext = this;
        etSearch = findViewById(R.id.et_face_pick_search);
        btSearch = findViewById(R.id.bt_face_pick_search);
        tvName = findViewById(R.id.tv_face_pick_ticket_name);
        tvNumber = findViewById(R.id.tv_face_pick_ticket_number);

        tvTicketType = findViewById(R.id.tv_face_ticket_type);
        tvTicketNumber = findViewById(R.id.tv_face_ticket_number);

        tvFace = findViewById(R.id.tv_face_pick_have_face);
        imFaceShow = findViewById(R.id.im_face_pick_face_show);

        btFaceGoto = findViewById(R.id.bt_face_pick_goto);
        btFaceOver = findViewById(R.id.bt_face_pick_over);

        llTicketRrsultShow = findViewById(R.id.ll_ticket_info_show);
        llbtShow = findViewById(R.id.ll_button_show);

        rvFaceShow = findViewById(R.id.rv_face_pick_list);

        searchAdapter = new SearchFaceAdapter(this, searchDate);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvFaceShow.setLayoutManager(linearLayoutManager);
        rvFaceShow.setAdapter(searchAdapter);


        doThing();

        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);
        //开启身份证读卡器
        if (bopen) {
            return;
        }
        RequestDevicePermission();

        searchAdapter.setfaceAddListener(new SearchFaceAdapter.SetfaceAdd() {
            @Override
            public void faceAdd(QufuQueryStaffReceiveTicketResultBean.DataBean dataBean) {
                llTicketRrsultShow.setVisibility(View.VISIBLE);
                rvFaceShow.setVisibility(View.GONE);
                if (dataBean != null) {
                    showSingFace(dataBean);
                } else {
                    SelfToastUtil.getInstance().show("未查询到数据");
                }
            }
        });

    }

    private void doThing() {

        btFaceOver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btFaceGoto.setOnClickListener(new View.OnClickListener() {

            private Intent intent;

            @Override
            public void onClick(View v) {
                if (tvName.getText().toString().length() > 5 && !StringUtil.isNullOrEmpty(certificateNo)) {
                    //说明查询成功，可以进行下一步
                    intent = new Intent(FacePickActivity.this, FaceSaveActivity.class);
                    intent.putExtra("certificateNo", certificateNo);
                    intent.putExtra("ComeFrom", "FacePickActivity");
                    startActivity(intent);
                } else {
                    SelfToastUtil.getInstance().show("请先选择需要人脸采集的条目");
                }

            }
        });

        btSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isNullOrEmpty(etSearch.getText().toString())) {
                    SelfToastUtil.getInstance().show("请输入票号或者证件号");
                    return;
                }
                certificateNo = "";
                tvName.setText("");
                tvNumber.setText("");
                tvTicketType.setText("");
                tvTicketNumber.setText("");
                Glide.with(FacePickActivity.this)
                        .load(R.mipmap.facebgs)
                        .placeholder(R.mipmap.facebgs)
                        .into(imFaceShow);
                // 如果有数据，那么就去查询
                goToSearch(etSearch.getText().toString());
            }
        });

    }

    private void goToSearch(String inputId) {
        DialogTipShow("请稍等。。。");
        QufuQueryStaffReceiveTicketRequsetBean staffReceiveTicketRequsetBean = new QufuQueryStaffReceiveTicketRequsetBean();
        staffReceiveTicketRequsetBean.setCertificateNo(inputId);

        RetrofitClient.getInstance(FacePickActivity.this, BASE_URL, headers).findOrderByCertificateNo(staffReceiveTicketRequsetBean, new BaseSubscriber<QufuQueryStaffReceiveTicketResultBean>(FacePickActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
                DiglogTipDiss();
            }

            @Override
            public void onNext(QufuQueryStaffReceiveTicketResultBean qufuQueryStaffReceiveTicketResultBean) {
                DiglogTipDiss();
                String code = qufuQueryStaffReceiveTicketResultBean.getCode();
                if (code.equals("200")) {
//                    certificateNo = etSearch.getText().toString();
                    if (qufuQueryStaffReceiveTicketResultBean.getData() != null && qufuQueryStaffReceiveTicketResultBean.getData().size() >= 0) {
                        if (qufuQueryStaffReceiveTicketResultBean.getData().size() == 1) {
                            llTicketRrsultShow.setVisibility(View.VISIBLE);
                            rvFaceShow.setVisibility(View.GONE);
                            QufuQueryStaffReceiveTicketResultBean.DataBean dataBean = qufuQueryStaffReceiveTicketResultBean.getData().get(0);

                            if (dataBean != null) {
                                showSingFace(dataBean);
                            } else {
                                SelfToastUtil.getInstance().show("未查询到数据");
                            }
                        } else if (qufuQueryStaffReceiveTicketResultBean.getData().size() == 0) {
                            //非实名制

                        } else {
                            //数据长度大于1 ，那么就先显示列表
                            llTicketRrsultShow.setVisibility(View.GONE);
                            rvFaceShow.setVisibility(View.VISIBLE);
                            searchDate.clear();
                            searchDate.addAll(qufuQueryStaffReceiveTicketResultBean.getData());
                            searchAdapter.notifyDataSetChanged();
                        }

                    } else {
                        SelfToastUtil.getInstance().show("该证件号暂无记录，请重新输入查询信息");
                    }

                } else {
                    SelfToastUtil.getInstance().show(qufuQueryStaffReceiveTicketResultBean.getMessage());
                }
            }
        });

    }

    private void showSingFace(QufuQueryStaffReceiveTicketResultBean.DataBean dataBean) {
        if (!StringUtil.isNullOrEmpty(dataBean.getScenicTicketName())) {
            tvName.setText("票名称: " + dataBean.getScenicTicketName());
        }

        if (!StringUtil.isNullOrEmpty(dataBean.getTickerNum() + "")) {
            tvNumber.setText("票人数: " + dataBean.getTickerNum());
        }

        if (!StringUtil.isNullOrEmpty(dataBean.getCertificateNo())) {
            certificateNo = dataBean.getCertificateNo();
            tvTicketType.setVisibility(View.VISIBLE);
            tvTicketNumber.setVisibility(View.VISIBLE);
            if (!StringUtil.isNullOrEmpty(dataBean.getCertificateTypeName())) {
                tvTicketType.setText("证件类型: " + dataBean.getCertificateTypeName());
            }
            if (!StringUtil.isNullOrEmpty(dataBean.getCertificateNo())) {
                tvTicketNumber.setText("证件号码: " + dataBean.getCertificateNo());
            }

        } else {
            //原始码  非实名制使用
            certificateNo = dataBean.getBarcodeNo();
            tvTicketType.setVisibility(View.GONE);
            tvTicketNumber.setVisibility(View.GONE);
        }

        if (StringUtil.isNullOrEmpty(dataBean.getFacePicPath())) {
            String str = "<font color = \"#000000\">已采集人脸信息       </font><font color = \"#FF1616\">0/1</font>";
            tvFace.setText(Html.fromHtml(str));
        } else {
            String str = "<font color = \"#000000\">已采集人脸信息       </font><font color = \"#FF1616\">1/1</font>";
            tvFace.setText(Html.fromHtml(str));
            Glide.with(FacePickActivity.this)
                    .load(dataBean.getFacePicPath())
                    .placeholder(R.mipmap.facebgs)
                    .into(imFaceShow);
        }

    }


    public void OpenDevice() {
        if (bopen) {
            SelfToastUtil.getInstance().show("设备已连接");
            return;
        }
        try {
            startIDCardReader();
            IDCardReaderExceptionListener listener = new IDCardReaderExceptionListener() {
                @Override
                public void OnException() {
                    //出现异常，关闭设备
                    CloseDevice();
                    //当前线程为工作线程，若需操作界面，请在UI线程处理
                    runOnUiThread(new Runnable() {
                        public void run() {
                            SelfToastUtil.getInstance().show("设备发生异常，断开连接！");
                        }
                    });
                }
            };
            idCardReader.open(0);
            idCardReader.setIdCardReaderExceptionListener(listener);
            bStoped = false;
            mReadCount = 0;
            writeLogToFile("连接设备成功");
//            SelfToastUtil.getInstance().show("连接成功");
            bopen = true;
            countdownLatch = new CountDownLatch(1);
            new Thread(new Runnable() {
                public void run() {
                    while (!bStoped) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        boolean ret = false;
                        final long nTickstart = System.currentTimeMillis();
                        try {
                            idCardReader.findCard(0);
                            idCardReader.selectCard(0);
                        } catch (Exception e) {  //IDCardReaderException
                            //continue;
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int retType = 0;
                        try {
                            retType = idCardReader.readCardEx(0, 0);
                        } catch (IDCardReaderException e) {
                            writeLogToFile("读卡失败，错误信息：" + e.getMessage());
                        } catch (Exception e) {

                        }
                        if (retType == 1 || retType == 2 || retType == 3) {
                            final long nTickUsed = (System.currentTimeMillis() - nTickstart);
                            final int final_retType = retType;
                            writeLogToFile("读卡成功：" + (++mReadCount) + "次" + "，耗时：" + nTickUsed + "毫秒");
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    if (final_retType == 1) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名adb
                                        final String strName = idCardInfo.getName();
                                        //民族
                                        String strNation = idCardInfo.getNation();
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        final String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        final String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();

                                        final String Sex = idCardInfo.getSex();


                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {

                                                timeNew = TimeUtil.getLocationTimeLong();
                                                if (!checkIDAgain(strID)) {
                                                    //如果正常10秒外，我才去显示以及请求
                                                    etSearch.setText("");
                                                    etSearch.setText(strID);
                                                }

                                            }
                                        });

                                    } else if (final_retType == 2) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
                                        //中文名
                                        String strCnName = idprpCardInfo.getCnName();
                                        //英文名
                                        String strEnName = idprpCardInfo.getEnName();
                                        //国家/国家地区代码
                                        String strCountry = idprpCardInfo.getCountry() + "/" + idprpCardInfo.getCountryCode();//国家/国家地区代码
                                        //出生日期
                                        String strBorn = idprpCardInfo.getBirth();
                                        //身份证号
                                        String strID = idprpCardInfo.getId();
                                        //有效期限
                                        String strEffext = idprpCardInfo.getValidityTime();


                                    } else {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名
                                        String strName = idCardInfo.getName();
                                        //民族,港澳台不支持该项
                                        String strNation = "";
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();
                                        //签发机关
                                        String strIssueAt = idCardInfo.getDepart();
                                        //通行证号
                                        String strPassNum = idCardInfo.getPassNum();
                                        //签证次数
                                        int visaTimes = idCardInfo.getVisaTimes();


                                    }
                                }
                            });
                        }
                    }
                    countdownLatch.countDown();
                }
            }).start();
        } catch (IDCardReaderException e) {
            SelfToastUtil.getInstance().show("连接设备失败");
        }
    }

    // 返回 true  相同 小于  10 秒  那么就 不处理
    private boolean checkIDAgain(String m_strIDCards) {
        if (m_strIDCards.equals(OldID) && timeNew - timeOld < 1000 * 5) {
            System.out.println("zyf  未超过30秒 拒绝访问" + TimeUtil.getLocationTime());
            return true;
        } else {
            System.out.println("zyf  超过30秒 去访问" + TimeUtil.getLocationTime());
            timeOld = timeNew;
            OldID = m_strIDCards;
            return false;
        }
    }

    private void CloseDevice() {
        if (!bopen) {
            return;
        }
        bStoped = true;
        mReadCount = 0;
        if (null != countdownLatch) {
            try {
                countdownLatch.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            idCardReader.close(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
        bopen = false;
    }

    private void startIDCardReader() {
        if (null != idCardReader) {
            IDCardReaderFactory.destroy(idCardReader);
            idCardReader = null;
        }
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);
    }

    public static void writeLogToFile(String log) {
        try {
            File dirFile = new File("/sdcard/zkteco/");  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            String path = "/sdcard/zkteco/idrlog.txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file, true);
            log += "\r\n";
            outStream.write(log.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void RequestDevicePermission() {
        musbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);

        for (UsbDevice device : musbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == PID) {
                Intent intent = new Intent(ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                musbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IDCardReaderFactory.destroy(idCardReader);
        mContext.unregisterReceiver(mUsbReceiver);
    }
}
